package com.alm.token.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.base.BaseAdapter;
import com.alm.token.common.RefreshLoadMoreManager;
import com.alm.token.ui.data.bean.ChannelTypeData;
import com.alm.token.ui.data.bean.LeHuoBaoListData;
import com.alm.token.ui.data.bean.RegisterData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.LeHuoBaoView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;
import com.alm.token.widget.CustomTabLayout;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BillActivity extends BaseActivity implements LeHuoBaoView<Object> {
    @BindView(R.id.centerItem)
    TextView centerItem;
    @BindView(R.id.rightItem)
    TextView rightItem;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.tab)
    CustomTabLayout tab;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.tv_clickreload)
    TextView tvClickreload;
    @BindView(R.id.nodatashow_body)
    RelativeLayout nodatashowBody;

    private RefreshLoadMoreManager<LeHuoBaoListData.DataBeanX.ListBean.DataBean> manager;

    private List<ChannelTypeData.DataBean.ChannelListBean> channelListBeans = new ArrayList<>();//name : 锁仓
    private List<ChannelTypeData.DataBean.MoneyTypeListBean> moneyTypeListBeans = new ArrayList<>();//name : ETH
    private List<ChannelTypeData.DataBean.IncomeTypeListBean> incomeTypeListBeans = new ArrayList<>();//name : 收入
    private List<LeHuoBaoListData.DataBeanX.ListBean.DataBean> dataBeanList = new ArrayList<>();
    private int channelListBeansType, moneyTypeListBeansType, incomeTypeListBeansType;

    private String orderId, limit, page, channelType, moneyType, incomeType;
    private String tabName1, tabName2, tabName3;

    @Override
    protected MyPreenter initPreenter() {
        return new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_bill;
    }

    @Override
    protected void initVariables() {
        new ActionBarHelper(this).setTitle(getString(R.string.title_hint_item1));
    }

    @Override
    protected void initViews() {
        ChannelTypeData.DataBean dataBean = MyApp.getChannelTypeDataBean();
        if (dataBean != null) {

            ChannelTypeData.DataBean.ChannelListBean bean = new ChannelTypeData.DataBean.ChannelListBean();
            bean.setName(getString(R.string.profile_hint_item11));
            bean.setType(0);
            channelListBeans.add(0, bean);
            channelListBeans.addAll(dataBean.getChannelList());


            ChannelTypeData.DataBean.MoneyTypeListBean bean1 = new ChannelTypeData.DataBean.MoneyTypeListBean();
            bean1.setName(getString(R.string.profile_hint_item11));
            bean1.setType(0);
            moneyTypeListBeans.add(0, bean1);
            moneyTypeListBeans.addAll(dataBean.getMoneyTypeList());

            ChannelTypeData.DataBean.IncomeTypeListBean bean2 = new ChannelTypeData.DataBean.IncomeTypeListBean();
            bean2.setName(getString(R.string.profile_hint_item11));
            bean2.setType(0);
            incomeTypeListBeans.add(0, bean2);
            incomeTypeListBeans.addAll(dataBean.getIncomeTypeList());
        }

        orderId = "";
        limit = "100";
        page = "1";
        channelType = channelListBeans != null && channelListBeans.size() != 0 ? channelListBeans.get(0).getType() + "" : "";
        moneyType = moneyTypeListBeans != null && moneyTypeListBeans.size() != 0 ? moneyTypeListBeans.get(0).getType() + "" : "";
        incomeType = incomeTypeListBeans != null && incomeTypeListBeans.size() != 0 ? incomeTypeListBeans.get(0).getType() + "" : "";

        String[] tabNames = {channelListBeans != null && channelListBeans.size() != 0 ? channelListBeans.get(0).getName() : getString(R.string.profile_hint_item11),
                moneyTypeListBeans != null && moneyTypeListBeans.size() != 0 ? moneyTypeListBeans.get(0).getName() + "" : getString(R.string.profile_hint_item11),
                incomeTypeListBeans != null && incomeTypeListBeans.size() != 0 ? incomeTypeListBeans.get(0).getName() + "" : getString(R.string.profile_hint_item11)};
        tabName1 = tabNames[0];
        tabName2 = tabNames[1];
        tabName3 = tabNames[2];
        tab.setItemLayout(R.layout.item_income_expend_tab);
        tab.setTabNames(tabNames);
        tab.setTabCall(new CustomTabLayout.TabCall() {
            @Override
            public void item(int position, FrameLayout frameLayout) {
                if (position == 0) {
                    showPopupMenu1(frameLayout);
                } else if (position == 1)
                    showPopupMenu2(frameLayout);
                else
                    showPopupMenu3(frameLayout);

            }
        });
        tab.notifyChange();

        initManager();
        swipeRefreshLayout.setVisibility(View.GONE);
    }

    private void initManager() {
        IncomeAdapter adapter = new IncomeAdapter(this);
        manager = new RefreshLoadMoreManager.Builder(this)
                .setAdapter(adapter)
                .setRecyclerView(recyclerView)
                .setOnListItemClickListener(new RefreshLoadMoreManager.OnListItemClickListener() {
                    @Override
                    public void onListItemClick(BaseAdapter.BaseItem item, int position) {
//                        if (dataBeansGuanbi != null && dataBeansGuanbi.size() > position) {
//                            Intent intent = new Intent(QuantitativeOrderCloseListActivity.this, QuantitativeOrderDetailActivity.class);
//                            intent.putExtra("databean", dataBeansGuanbi.get(position));
//                            startActivityForResult(intent, ActivityForResultCode);
//                        }
//                        startActivity(QuantitativeOrderDetailActivity.class);
                    }
                })
                .setSwipeRefreshLayout(swipeRefreshLayout)
                .setOnRefreshListener(new RefreshLoadMoreManager.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
//                        showToast("onRefresh");
                        swipeRefreshLayout.setRefreshing(false);
                        mathRequest();
//                        preenter.getLeHuoBaoListData(orderId, limit, page, channelType, moneyType, incomeType);
                    }
                })
                .setOpenLoadMore(true)
                .setOnLoadMoreListener(new RefreshLoadMoreManager.OnLoadMoreListener() {

                    @Override
                    public void onLoadMore() {
                        manager.getAdapter().loadMoreEnd(true);
                        manager.getAdapter().loadMoreFail();
//                        if(dataBeans.size()!=9){
//                            dataBeans.clear();
//                        }
                        showWaitDialog();
//                        loadMoreData(ticker);
                        preenter.getLeHuoBaoListData(orderId, limit, page, channelType, moneyType, incomeType);

                    }
                })
                .build();

        recyclerView.setNestedScrollingEnabled(false);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (EmptyUtils.isNotEmpty(dataBeanList) && dataBeanList.size() > position) {
                    Intent intent = new Intent(BillActivity.this, LogDetailActivity.class);
                    intent.putExtra("LogDetailActivity_type", LogDetailActivity.BILL_TYPE);
                    intent.putExtra("LogDetailActivity_id", dataBeanList.get(position).getId());
                    startActivity(intent);
                }
            }
        });
    }


    public void mathRequest() {
        limit = "100";
        page = "1";

        preenter.getLeHuoBaoListData(orderId, limit, page, channelType, moneyType, incomeType);
    }

    @Override
    protected void loadData() {
        /**
         * @param orderId     量化订单id
         * @param limit       条数 100
         * @param page        页数  1
         * @param channelType 收益类型，全部传null值
         * @param moneyType   金额类型
         * @param incomeType  收入支出类型
         */

        orderId = "";
        limit = "100";
        page = "1";
        channelType = "";
        moneyType = "";
        incomeType = "";
        preenter.getLeHuoBaoListData(orderId, limit, page, channelType, moneyType, incomeType);

//        manager.setData(getTestData());
    }

    @Override
    public void onClick(View v) {

    }

    private boolean isfull = false;
    private List<LeHuoBaoListData.DataBeanX.ListBean.DataBean> dataBeanListold = new ArrayList<>();

    @Override
    public void getLeHuoBaoListData(LeHuoBaoListData leHuoBaoListData) {

        if (leHuoBaoListData.getStatus() == 0 && leHuoBaoListData.getData() != null && leHuoBaoListData.getData().getList() != null && leHuoBaoListData.getData().getList().getData() != null) {
            if (Integer.valueOf(page) == 1) {
                dataBeanList.clear();
            } else if (!isfull && dataBeanList.size() > (Integer.valueOf(page) - 1) * 100) {
                dataBeanList.removeAll(dataBeanListold);
            }
//            dataBeanList.clear();
            if (leHuoBaoListData.getData().getList().getData().size() == 100) {
                isfull = true;
                page = String.valueOf(Integer.valueOf(page) + 1);
            } else {
                isfull = false;
            }

            dataBeanListold = leHuoBaoListData.getData().getList().getData();
            dataBeanList.addAll(leHuoBaoListData.getData().getList().getData());
            for (int i = 0; i < dataBeanList.size(); i++) {
                dataBeanList.get(i).setLayoutId(IncomeAdapter.LAYOUT_ID);
            }
            manager.setData(dataBeanList);
        } else {
            showToast(leHuoBaoListData.getMsg());
        }

        if (dataBeanList.size() == 0) {
            swipeRefreshLayout.setVisibility(View.GONE);
            nodatashowBody.setVisibility(View.VISIBLE);
        } else {
            swipeRefreshLayout.setVisibility(View.VISIBLE);
            nodatashowBody.setVisibility(View.GONE);
        }

    }

    @Override
    public void getLeHuoTopUpsData(RegisterData leHuoTopUpsData) {

    }

    @Override
    public void getData(Object o) {

    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(this,PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            finish();
            showToSetPaypswDialog();
        } else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {
        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {

        showWaitDialog();
    }

    @Override
    public void hideProgress() {
        hideWaitDialog();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.tv_clickreload)
    public void onViewClicked() {


        mathRequest();
//        preenter.getLeHuoBaoListData(orderId, limit, page, channelType, moneyType, incomeType);
    }


    public class IncomeAdapter extends BaseAdapter<LeHuoBaoListData.DataBeanX.ListBean.DataBean> {

        public static final int LAYOUT_ID = R.layout.item_income_expend;

        public IncomeAdapter(@NonNull Context context) {
            super(context);
        }

        @Override
        protected void convert(BaseViewHolder helper, LeHuoBaoListData.DataBeanX.ListBean.DataBean dataBean, int itemType) {
            helper.setText(R.id.tv_channelType, dataBean.getChannelTypeStr() + "");
            helper.setText(R.id.tv_createTime, CommonUtil.getDateTimeFromMillisecond(dataBean.getUpdateTime() != 0 ? dataBean.getUpdateTime() : dataBean.getCreateTime()));

            double money = dataBean.getMoney();
            if (money < 0) {
                helper.setTextColor(R.id.tv_money, getResources().getColor(R.color.lehuobao_zhichu));
                helper.setImageDrawable(R.id.icon, getResources().getDrawable(R.drawable.icom_outdown));
                helper.setText(R.id.tv_money, CommonUtil.saveToPoint4WithNo(money));
            } else {
                helper.setTextColor(R.id.tv_money, getResources().getColor(R.color.colorgreen1));
                helper.setImageDrawable(R.id.icon, getResources().getDrawable(R.drawable.icom_getup));
                helper.setText(R.id.tv_money, "+" + CommonUtil.saveToPoint4WithNo(money));
            }
        }

    }

    public void showPopupMenu1(View view) {
        //参数View 是设置当前菜单显示的相对于View组件位置，具体位置系统会处理
        PopupMenu popupMenu = new PopupMenu(this, view);
        //加载menu布局
        Menu menu = popupMenu.getMenu();
        for (ChannelTypeData.DataBean.ChannelListBean channelListBean : channelListBeans) {
            if (!tabName1.equalsIgnoreCase(channelListBean.getName())) {
                menu.add(channelListBean.getName());
            }
        }
        popupMenu.getMenuInflater().inflate(R.menu.menu_popmenu, menu);
//        popupMenu.set

        //设置menu中的item点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                for (int i = 0; i < channelListBeans.size(); i++) {
                    if (item.getTitle().toString().equalsIgnoreCase(channelListBeans.get(i).getName())) {
                        if (channelListBeansType != channelListBeans.get(i).getType()) {
                            channelListBeansType = channelListBeans.get(i).getType();//0 全部  1 2 3
                            channelType = channelListBeansType + "";
                            tabName1 = item.getTitle().toString();
                            tab.setTabTitle(0, item.getTitle().toString());
                            mathRequest();
                        }
                        break;
                    }
                }
                return true;
            }
        });
        popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
            @Override
            public void onDismiss(PopupMenu menu) {
                // 控件消失时的事件
            }
        });


        popupMenu.show();
    }

    public void showPopupMenu2(View view) {
        //参数View 是设置当前菜单显示的相对于View组件位置，具体位置系统会处理
        PopupMenu popupMenu = new PopupMenu(this, view);
        //加载menu布局
        Menu menu = popupMenu.getMenu();
        for (ChannelTypeData.DataBean.MoneyTypeListBean moneyTypeListBean : moneyTypeListBeans) {
            if (!tabName2.equalsIgnoreCase(moneyTypeListBean.getName())) {
                menu.add(moneyTypeListBean.getName());
            }
        }
        popupMenu.getMenuInflater().inflate(R.menu.menu_popmenu, menu);


        //设置menu中的item点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                for (int i = 0; i < moneyTypeListBeans.size(); i++) {
                    if (item.getTitle().toString().equalsIgnoreCase(moneyTypeListBeans.get(i).getName())) {
                        if (moneyTypeListBeansType != moneyTypeListBeans.get(i).getType()) {
                            moneyTypeListBeansType = moneyTypeListBeans.get(i).getType();//0 全部  1 2 3
                            moneyType = moneyTypeListBeansType + "";
                            tabName2 = item.getTitle().toString();
                            tab.setTabTitle(1, item.getTitle().toString());
                            mathRequest();
                        }
                        break;
                    }
                }
                return true;
            }
        });
        popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
            @Override
            public void onDismiss(PopupMenu menu) {
                // 控件消失时的事件
            }
        });
        popupMenu.show();
    }

    ////    channelListBeansType,moneyTypeListBeansType,incomeTypeListBeansType
    public void showPopupMenu3(View view) {
        //参数View 是设置当前菜单显示的相对于View组件位置，具体位置系统会处理
        PopupMenu popupMenu = new PopupMenu(this, view);
        //加载menu布局
        Menu menu = popupMenu.getMenu();
        for (ChannelTypeData.DataBean.IncomeTypeListBean incomeTypeListBean : incomeTypeListBeans) {
            if (!tabName3.equalsIgnoreCase(incomeTypeListBean.getName())) {
                menu.add(incomeTypeListBean.getName());
            }
        }
        popupMenu.getMenuInflater().inflate(R.menu.menu_popmenu, menu);


        //设置menu中的item点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                for (int i = 0; i < incomeTypeListBeans.size(); i++) {
                    if (item.getTitle().toString().equalsIgnoreCase(incomeTypeListBeans.get(i).getName())) {

                        if (incomeTypeListBeansType != incomeTypeListBeans.get(i).getType()) {
                            incomeTypeListBeansType = incomeTypeListBeans.get(i).getType();//0 全部  1 2 3
                            incomeType = incomeTypeListBeansType + "";
                            tabName3 = item.getTitle().toString();
                            tab.setTabTitle(2, item.getTitle().toString());
                            mathRequest();
                        }
                        break;
                    }
                }
                return true;
            }
        });
        popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
            @Override
            public void onDismiss(PopupMenu menu) {
                // 控件消失时的事件
            }
        });
        popupMenu.show();
    }
}
